package cn.tedu.smartos.health.service;

import cn.tedu.smartos.health.pojo.entity.HealthData;
import cn.tedu.smartos.family_user.service.ElderlyBindService;
import cn.tedu.smartos.health.service.HealthAlertService;
import cn.tedu.smartos.health.pojo.dto.HealthAlertParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class HealthAlertDetectionService {

    @Autowired
    private HealthAlertService healthAlertService;

    @Autowired
    private ElderlyBindService elderlyBindService;

    // 健康指标正常范围阈值
    private static final int HEART_RATE_MIN = 60;
    private static final int HEART_RATE_MAX = 100;
    private static final int BLOOD_PRESSURE_SYSTOLIC_MIN = 90;
    private static final int BLOOD_PRESSURE_SYSTOLIC_MAX = 140;
    private static final int BLOOD_PRESSURE_DIASTOLIC_MIN = 60;
    private static final int BLOOD_PRESSURE_DIASTOLIC_MAX = 90;
    private static final double BLOOD_SUGAR_MIN = 3.9;
    private static final double BLOOD_SUGAR_MAX = 6.1;
    private static final int BLOOD_OXYGEN_MIN = 95;
    private static final double TEMPERATURE_MIN = 36.0;
    private static final double TEMPERATURE_MAX = 37.2;

    /**
     * 检测健康数据异常并生成预警
     */
    public void detectAndCreateAlert(HealthData healthData) {
        if (healthData.getIsNormal() != null && healthData.getIsNormal() == 1) {
            return; // 标记为正常的数据无需处理
        }

        boolean isAbnormal = false;
        String alertContent = "";
        int alertType = 0;
        int alertLevel = 2; // 默认中级预警

        switch (healthData.getDataType()) {
            case 1: // 心率
                int heartRate = Integer.parseInt(healthData.getDataValue());
                if (heartRate < HEART_RATE_MIN || heartRate > HEART_RATE_MAX) {
                    isAbnormal = true;
                    alertType = 1;
                    alertContent = String.format("心率异常: %d次/分 (正常范围: %d-%d次/分)",
                            heartRate, HEART_RATE_MIN, HEART_RATE_MAX);

                    // 设置预警级别
                    if (heartRate < 50 || heartRate > 120) {
                        alertLevel = 3; // 高级预警
                    }
                }
                break;

            case 2: // 血压
                String[] bpValues = healthData.getDataValue().split("/");
                if (bpValues.length == 2) {
                    int systolic = Integer.parseInt(bpValues[0]);
                    int diastolic = Integer.parseInt(bpValues[1]);

                    if (systolic < BLOOD_PRESSURE_SYSTOLIC_MIN ||
                            systolic > BLOOD_PRESSURE_SYSTOLIC_MAX ||
                            diastolic < BLOOD_PRESSURE_DIASTOLIC_MIN ||
                            diastolic > BLOOD_PRESSURE_DIASTOLIC_MAX) {

                        isAbnormal = true;
                        alertType = 2;
                        alertContent = String.format("血压异常: %d/%dmmHg (正常范围: %d-%d/%d-%dmmHg)",
                                systolic, diastolic,
                                BLOOD_PRESSURE_SYSTOLIC_MIN, BLOOD_PRESSURE_SYSTOLIC_MAX,
                                BLOOD_PRESSURE_DIASTOLIC_MIN, BLOOD_PRESSURE_DIASTOLIC_MAX);

                        // 设置预警级别
                        if (systolic > 160 || diastolic > 100 || systolic < 80 || diastolic < 50) {
                            alertLevel = 3; // 高级预警
                        }
                    }
                }
                break;

            case 3: // 血糖
                double bloodSugar = Double.parseDouble(healthData.getDataValue());
                if (bloodSugar < BLOOD_SUGAR_MIN || bloodSugar > BLOOD_SUGAR_MAX) {
                    isAbnormal = true;
                    alertType = 3;
                    alertContent = String.format("血糖异常: %.1fmmol/L (正常范围: %.1f-%.1fmmol/L)",
                            bloodSugar, BLOOD_SUGAR_MIN, BLOOD_SUGAR_MAX);

                    // 设置预警级别
                    if (bloodSugar < 3.0 || bloodSugar > 10.0) {
                        alertLevel = 3; // 高级预警
                    }
                }
                break;

            case 4: // 血氧
                int bloodOxygen = Integer.parseInt(healthData.getDataValue());
                if (bloodOxygen < BLOOD_OXYGEN_MIN) {
                    isAbnormal = true;
                    alertType = 4;
                    alertContent = String.format("血氧异常: %d%% (正常范围: ≥%d%%)",
                            bloodOxygen, BLOOD_OXYGEN_MIN);
                    alertLevel = bloodOxygen < 90 ? 3 : 2; // <90%为高级预警
                }
                break;

            case 5: // 体温
                double temperature = Double.parseDouble(healthData.getDataValue());
                if (temperature < TEMPERATURE_MIN || temperature > TEMPERATURE_MAX) {
                    isAbnormal = true;
                    alertType = 5;
                    alertContent = String.format("体温异常: %.1f℃ (正常范围: %.1f-%.1f℃)",
                            temperature, TEMPERATURE_MIN, TEMPERATURE_MAX);
                    alertLevel = temperature > 38.0 || temperature < 35.0 ? 3 : 2;
                }
                break;
        }

        if (isAbnormal) {
            createHealthAlerts(healthData, alertType, alertLevel, alertContent);
        }
    }

    /**
     * 创建健康数据异常预警
     */
    public boolean isDataNormal(HealthData healthData) {
        switch (healthData.getDataType()) {
            case 1:
                int heartRate = Integer.parseInt(healthData.getDataValue());
                return heartRate >= 60 && heartRate <= 100;
            case 2:
                String[] bp = healthData.getDataValue().split("/");
                int systolic = Integer.parseInt(bp[0]);
                int diastolic = Integer.parseInt(bp[1]);
                return systolic >= 90 && systolic <= 140 && diastolic >= 60 && diastolic <= 90;
            case 3:
                double sugar = Double.parseDouble(healthData.getDataValue());
                return sugar >= 3.9 && sugar <= 6.1;
            case 4:
                int oxygen = Integer.parseInt(healthData.getDataValue());
                return oxygen >= 95;
            case 5:
                double temp = Double.parseDouble(healthData.getDataValue());
                return temp >= 36.0 && temp <= 37.2;
            default:
                return true;
        }
    }


    /**
     * 为绑定的家属创建健康预警
     */
    private void createHealthAlerts(HealthData healthData, int alertType, int alertLevel, String alertContent) {
        // 获取绑定该老人的所有家属ID
        List<Long> familyUserIds = elderlyBindService.getFamilyUserIdsByElderlyId(healthData.getElderlyUserId());

        if (familyUserIds.isEmpty()) {
            log.warn("未找到绑定老人ID:{}的家属", healthData.getElderlyUserId());
            return;
        }

        // 为每个家属创建预警记录
        for (Long familyUserId : familyUserIds) {
            HealthAlertParam alertParam = new HealthAlertParam();
            alertParam.setElderlyUserId(healthData.getElderlyUserId());
            alertParam.setRecordId(healthData.getRecordId());
            alertParam.setAlertType(alertType);
            alertParam.setAlertLevel(alertLevel);
            alertParam.setAlertContent(alertContent);
            alertParam.setNotifyFamilyId(familyUserId);

            try {
                healthAlertService.createAlert(alertParam);
                log.info("已为家属ID:{}创建健康预警: {}", familyUserId, alertContent);
            } catch (Exception e) {
                log.error("为家属ID:{}创建健康预警失败", familyUserId, e);
            }
        }
    }
}